package yxy.game.pm2.active.command.payday;

import org.joda.time.DateTime;
import yxy.cherry.data.bean.actrecharge;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.active.module.ActiveModule_累充天数;
import yxy.game.pm2.active.module.actdata.ActDataCenter;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ActiveMessage;
import yxy.game.pm2.message.ActiveMessage.ActPayDayDrawRewardRequest;
import yxy.game.pm2.message.PackageMessage;
import yxy.game.pm2.module.CurrencyHandle;

import java.util.Collection;
import java.util.Map;

/**
 * 累冲天数奖励领取
 * @author Dell
 */
@MessageType(proto = Command.ActPayDayDrawReward, classtype = ActiveMessage.ActPayDayDrawRewardRequest.class)
public class CMD_Active_累冲天数_DrawReward extends Command<ActPayDayDrawRewardRequest> {

	@Override
	public void execute(MessageSource messageSource, ActPayDayDrawRewardRequest request) throws Exception {
		String playercode = messageSource.getTag();
		int id = request.getId();
		ActiveMessage.ActPayDayDrawRewardResponse.Builder response = ActiveMessage.ActPayDayDrawRewardResponse.newBuilder();
		
		ActiveModule_累充天数 am = ActiveModule_累充天数.get(playercode,false);
		if(am == null) {
			send(messageSource, response, Result.ActNoOpen);
			return;
		}
		if(!am.running()) {
			send(messageSource, response, Result.ActNoOpen);
			return;
		}
		
		if(am.getGetids().contains(id)) {
			send(messageSource, response, Result.ActHadGet);
			return;
		}
		
		actrecharge execl = null;
		Map<String, actrecharge> armap = ActDataCenter.getAllData(actrecharge.class, playercode);
		for (actrecharge data : armap.values()) {
			if(data.getId() == id) {
				execl = data;
			}
		}
		
		if(execl == null) {
			send(messageSource, response, Result.DataError);
			return;
		}
		
		if(am.getDays() < execl.getCondition()) {
			send(messageSource, response, Result.ActCannotGet);
			return;
		}
		
		am.getGetids().add(id);
		am.setDrawtime(DateTime.now());
		am.set();

		Collection<Currency> curs = new Currency().create(execl.getRewardtype(), execl.getRewardid(), execl.getRewardnum());
		Collection<PackageMessage.Item> drawitems = new CurrencyHandle().packItems(curs);
		response.addAllDisplay(drawitems);
		
		//下发道具
		new CurrencyHandle().addCurrency(playercode, CCReason.活动_累冲天数, curs);
 		
		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, ActiveMessage.ActPayDayDrawRewardResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}
